<?php

namespace app\common\service\core;

use app\common\model\banxi\core\CoreAccountData;
use app\common\service\ApiService;
use ba\Exception;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Cache;

class CoreAccountDataService extends ApiService
{

    /**
     * 获取或创建账户
     * @param $accountId
     * @param $accountType
     * @return false|void
     */
    public function getByAccountIdAndType($accountId, $accountType)
    {
        if ($accountType == 1) {
            $this->setError('PLATFORM NOT ALLOWED');
            return false;
        }
        $coreAccountDataModel = new CoreAccountData();
        $accountData = $coreAccountDataModel->where([
            'accountType' => $accountType,
            'accountId' => $accountId,
        ])->find();
        if (!$accountData) {
            $key = "CoreAccountData:create:{$accountType}_{$accountId}";
            $isExists = Cache::has($key);
            if ($isExists) {
                $this->setError('账户操作繁忙，请稍后重试');
                return false;
            }
            Cache::set($key, 1, 3000);
            try {
                $accountData = $coreAccountDataModel->where([
                    'accountType' => $accountType,
                    'accountId' => $accountId,
                ])->find();
                if (!$accountData) {
                    $coreAccountDataModel->save([
                        'accountId' => $accountId,
                        'accountType' => $accountType,
                        'brokerageAmount' => 0
                    ]);
                    $accountData = $coreAccountDataModel->getData();
                }
            } catch (Exception|PDOException|ValidateException $e) {
                $this->setError($e->getMessage());
                return false;
            } finally {
                Cache::delete($key);
            }
        }
        return $accountData;


    }

    /**
     * 更新佣金余额
     * @return CoreAccountData
     */
    public function updateBrokerage($accountId, $accountType, $beforeValue, $afterValue)
    {
        $coreAccountDataModel = new CoreAccountData();
        return $coreAccountDataModel->update([
            'brokerageAmount' => $afterValue,
        ], [
            'accountId' => $accountId,
            'accountType' => $accountType,
            'brokerageAmount' => $beforeValue
        ]);
    }
}
